package com.fengye.middleware.rabbitmq.boot.ack.auto;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fengye.middleware.rabbitmq.boot.ack.KnowledgeInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 *
 * @author sky
 * @date 2021年06月09日 11:16 上午
 */
@Component
@Slf4j
public class KnowledgeAutoPublisher {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${mq.knowledge.auto.exchange.name:auto_change_name}")
    private String autoExchangeName;

    @Value("${mq.knowledge.auto.routing.key.name:auto_routing_key_name}")
    private String autoRoutingKeyName;


    // TODO: 接受乱码的问题
    public void sendMsg(KnowledgeInfo info) {
        if (info != null) {
            try {
                rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
                rabbitTemplate.setExchange(autoExchangeName);
                rabbitTemplate.setRoutingKey(autoRoutingKeyName);

                Message msg = MessageBuilder
                        .withBody(objectMapper.writeValueAsBytes(info))
                        .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                        .build();
                rabbitTemplate.convertAndSend(msg);

                log.info("基于 AUTO 机制：生产者-发送消息：{}", info);
            } catch (Exception e) {
                log.error("基于 AUTO 机制：生产者-发送消息异常：{}", info, e.fillInStackTrace());
            }
        }
    }
}
